import { Inject, Provide } from '@midwayjs/decorator';
import { IWebMiddleware, IMidwayWebNext } from '@midwayjs/web';
import { UserActionLogService } from '../service/log';
import { Context } from 'egg';

/**
 * 日志中间件
 */
@Provide()
export class UserActionLogMiddleware implements IWebMiddleware {
  @Inject()
  userActionLogService: UserActionLogService;

  resolve() {
    return async (ctx: Context, next: IMidwayWebNext) => {
      if (ctx.user) {
        this.userActionLogService.record(
          ctx,
          ctx.url.split('?')[0],
          ctx.req.method === 'GET' ? ctx.request.query : ctx.request.body,
          ctx.user ? ctx.user.id : null
        );
      }
      await next();
    };
  }
}
